package org.opendatakit.sensors.wifi;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;


public class ReceiverThread implements Runnable{

public static final int DGRAM_LENGTH = 1024;
//public static final int PORT = 5003;

//static String multicast_group = "225.4.5.6";


private DatagramSocket s;
private String mac;
private Context context;
private JSONObject json;
private boolean discovery;
static public AtomicBoolean discovering=new AtomicBoolean(true);
private static final int server_port = WifiAdapter.port;

public ReceiverThread(String mac, Context c){
	context=c;
	json = new JSONObject();
	this.mac = mac;
	ReceiverThread.discovering.set(true);
	if(mac=="")
		discovery=false;
	else
		discovery=true;
	try {
		//DatagramPacket p = new DatagramPacket(message, message.length);
		s = new DatagramSocket(server_port);
		Log.d("MST", s.toString());

	} catch (IOException e) {
		e.printStackTrace();
	}
	
	
	
}

public void run() {

	byte buf[] = new byte[1024];
	DatagramPacket pack;
	Log.d("running Reciever thread","blha");
	try {
		
		while(discovering.get()){
			Log.d("Waiting...","Waiting for packet");
			buf = new byte[1024];
			pack = new DatagramPacket(buf, buf.length);
			s.receive(pack);
			String received= new String(pack.getData());
			Log.d("packet1","received packet from " + pack.getAddress().getHostAddress());
			if(discovery){
				try {
					json=new JSONObject(received);
					//Log.d("Packet = ",json.toString());
					String nextPack;
					if(json.has("exec")){
						nextPack=json.getString("exec");
					}else{
						nextPack=json.getString("stat");
					}
					json=new JSONObject(nextPack);
					//Log.d("Packet in exec= ",json.toString());
					if(json.getString("sdr").compareTo(mac)!=0){
						Intent i = new Intent();
						i.setAction(WifiDevice.ACTION_FOUND); 
						Log.d("mac= ",json.getString("sdr"));
						i.putExtra("address", json.getString("sdr"));
						
						if(!json.isNull("ip")){
							i.putExtra("ip", json.getString("ip"));
						}else{
							InetAddress inet =pack.getAddress();
							i.putExtra("ip", inet.getHostAddress());
						}
						
						if(!json.isNull("name")){
						i.putExtra("name", json.getString("name"));
						}
						else{
							i.putExtra("name", "Flyport");
						}
						
						if(!json.isNull("port")){
							i.putExtra("port", json.getString("port"));
						}else{
							i.putExtra("port", "50000");
						}
						
						//Log.d("Receiver Thread", json.getString("name")+ json.getString("port"));	
						LocalBroadcastManager.getInstance(context).sendBroadcast(i);
						
	
					}
				}catch (JSONException e) {
					Log.d("JSONException","Unexpected format, will ignore packet.");
					e.printStackTrace();
					continue;
				}
			}
		}
		
	}catch (UnknownHostException e2) {
		e2.printStackTrace();
	}catch (IOException e) {	
		e.printStackTrace();
	}
	
	s.close();
	
}	
	
}